<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>新增订单</title>
    <link rel="stylesheet" href="/element-ui/index.css">
    <link rel="stylesheet" href="/element-ui/fonts/element-icons.css">
    <script src="/element-ui/vue.js"></script>
    <script src="/element-ui/index.js"></script>
    <script src="/element-ui/axios.min.js"></script>
    <style>
        body {
            font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '\\5FAE\\8F6F\\96C5\\9ED1', Arial, sans-serif;
            background-color: #f5f6fa;
        }
        #app {
            padding: 20px;
            background-color: #f5f6fa;
        }
        .page-title-bar {
            font-size: 26px;
            font-weight: bold;
            color: #333;
            background: #fff;
            padding: 24px 20px 12px 20px;
            border-bottom: 1px solid #eee;
            margin-bottom: 20px;
            letter-spacing: 2px;
            text-align: center;
            animation: fadeInDown 0.8s ease-out;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            border-radius: 8px;
        }
        @keyframes fadeInDown {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .el-main {
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        .el-form-item {
            margin-bottom: 22px;
        }
        .el-input__inner,
        .el-select .el-input__inner,
        .el-input-number .el-input__inner,
        .el-textarea__inner {
            transition: all 0.3s ease;
        }
        .el-input__inner:focus,
        .el-input__inner:hover,
        .el-select .el-input__inner:focus,
        .el-select .el-input__inner:hover,
        .el-input-number .el-input__inner:focus,
        .el-input-number .el-input__inner:hover,
        .el-textarea__inner:focus,
        .el-textarea__inner:hover {
            border-color: #409EFF;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }
        .el-button {
            transition: all 0.3s ease;
        }
        .el-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(64, 158, 255, 0.2);
        }
        .el-button--primary:hover,
        .el-button--danger:hover,
        .el-button--info:hover {
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
        }
        .box-card {
            margin-bottom: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            animation: fadeIn 1s ease-out;
        }
        .box-card .el-card__header {
            font-weight: bold;
            font-size: 18px;
            color: #333;
        }
        .order-detail-item {
            margin-bottom: 20px;
            padding-bottom: 20px;
            border-bottom: 1px dashed #dcdfe6;
            animation: slideInLeft 0.5s ease-out;
        }
        .order-detail-item:last-child {
            border-bottom: none;
        }
        @keyframes slideInLeft {
            from { opacity: 0; transform: translateX(-20px); }
            to { opacity: 1; transform: translateX(0); }
        }
        .order-total {
            margin-top: 20px;
            text-align: right;
            font-size: 16px;
        }
        .total-amount {
            color: #f56c6c;
            font-weight: bold;
            font-size: 20px;
            margin-left: 10px;
        }
        .submit-buttons {
            margin-top: 20px;
            text-align: center;
        }

        /* Responsive adjustments for smaller screens */
        @media (max-width: 767px) {
            .el-form-item__label {
                width: auto !important;
                float: none !important;
                text-align: left !important;
                padding-right: 0 !important;
            }
            .el-form-item__content {
                margin-left: 0 !important;
                line-height: normal; /* Ensure proper line height for stacked content */
            }
            .el-input-number {
                width: 100% !important;
            }
            /* Adjustments for order detail items on very small screens */
            .order-detail-item .el-col {
                margin-bottom: 15px; /* Add some space between stacked columns */
            }
            .order-detail-item .el-col:last-child {
                margin-bottom: 0;
            }
            .order-detail-item .el-form-item .el-form-item__content span {
                display: block;
                text-align: left; /* Align text to left if it's stacked */
            }
        }

        @media (max-width: 991px) and (min-width: 768px) {
            /* Adjustments for small to medium screens */
            .order-detail-item .el-col {
                margin-bottom: 10px; /* Adjust spacing for tablet size */
            }
            .order-detail-item .el-col:last-child {
                margin-bottom: 0;
            }
        }
    </style>
</head>
<body>
    <div class="page-title-bar">新增订单</div>
    <div id="app">
        <el-container>
            <el-main>
                <el-form :model="form" :rules="rules" ref="form" label-width="100px">
                    <!-- 订购人信息 -->
                    <el-card class="box-card">
                        <div slot="header" class="clearfix">
                            <span>订购人信息</span>
                        </div>
                        <el-form-item label="订购人" prop="userId">
                            <el-select v-model="form.userId" placeholder="请选择订购人" @change="handleUserChange">
                                <el-option
                                    v-for="user in users"
                                    :key="user.id"
                                    :label="(user.realName || user.username) + ' - ' + (user.department || '')"
                                    :value="user.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="联系电话" prop="phone">
                            <el-input v-model="form.phone" placeholder="请输入联系电话" :readonly="isNormalUser"></el-input>
                        </el-form-item>
                        <el-form-item label="专业" prop="major">
                            <el-input v-model="form.major" placeholder="自动带出" :readonly="true"></el-input>
                        </el-form-item>
                        <el-form-item label="学期" prop="term">
                            <el-select v-model="form.term" placeholder="请选择学期" @change="handleTermMajorChange">
                                <el-option label="2024春季" value="2024春季"></el-option>
                                <el-option label="2024秋季" value="2024秋季"></el-option>
                                <el-option label="2025春季" value="2025春季"></el-option>
                                <el-option label="2025秋季" value="2025秋季"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-card>

                    <!-- 订单明细 -->
                    <el-card class="box-card" style="margin-top: 20px;">
                        <div slot="header" class="clearfix">
                            <span>订单明细</span>
                            <el-button style="float: right; padding: 3px 0" type="text" @click="addOrderDetail">添加教材</el-button>
                        </div>
                        
                        <div v-for="(detail, index) in form.orderDetails" :key="index" class="order-detail-item">
                            <el-row :gutter="20">
                                <el-col :xs="24" :sm="24" :md="5">
                                    <el-form-item :label="'教材'" :prop="'orderDetails.' + index + '.bookId'" :rules="{ required: true, message: '请选择教材', trigger: 'change' }">
                                        <el-select v-model="detail.bookId" placeholder="请选择教材" @change="val => handleBookChange(val, index)">
                                            <el-option
                                                v-for="book in books"
                                                :key="book.bookId"
                                                :label="book.bookName + ' - ' + book.bookId"
                                                :value="book.bookId"
                                                :disabled="form.orderDetails.some((d, i) => i !== index && d.bookId === book.bookId)">
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :xs="24" :sm="24" :md="5" style="display: flex; align-items: center; height: 40px; font-size: 14px; color: #606266;">
                                    <span style="margin-right: 24px;">库存：<span style="font-weight: 500;">(( detail.stock !== undefined ? detail.stock : 'N/A' ))</span></span>
                                    <span>单价：<span style="font-weight: 500;">(( detail.price !== undefined ? detail.price : 0 ))</span></span>
                                </el-col>
                                <el-col :xs="24" :sm="24" :md="7">
                                    <el-form-item :label="'数量'" :prop="'orderDetails.' + index + '.quantity'" :rules="rules.quantity">
                                        <div style="display: flex; align-items: center; white-space: nowrap;">
                                            <el-input-number v-model="detail.quantity" :min="1" :max="1" style="width: 120px;" :disabled="!detail.bookId"></el-input-number>
                                        </div>
                                    </el-form-item>
                                </el-col>
                                <el-col :xs="24" :sm="24" :md="6">
                                    <el-form-item label="小计：">
                                        <span>(( (detail.price * detail.quantity) || 0 ))</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :xs="24" :sm="24" :md="2" style="display: flex; align-items: center; justify-content: center; height: 40px;">
                                    <el-button type="danger" icon="el-icon-delete" circle @click="removeOrderDetail(index)"></el-button>
                                </el-col>
                            </el-row>
                        </div>

                        <!-- 订单总计 -->
                        <div class="order-total">
                            <span>订单总计：</span>
                            <span class="total-amount">￥(( totalAmount ))</span>
                        </div>
                    </el-card>

                    <!-- 提交按钮 -->
                    <div class="submit-buttons">
                        <el-button @click="goBack">取消</el-button>
                        <el-button type="primary" @click="submitForm">提交订单</el-button>
                    </div>
                </el-form>
            </el-main>
        </el-container>
    </div>

    <script th:inline="javascript">
        window.currentUser = /*[[${user} == null ? '{}' : ${user}]]*/ {};
    </script>

    <script>
        new Vue({
            el: '#app',
            delimiters: ['((', '))'],
            data() {
                return {
                    form: {
                        userId: '',
                        realName: '',
                        phone: '',
                        orderDetails: [],
                        major: '',
                        term: ''
                    },
                    users: [],
                    books: [],
                    rules: {
                        userId: [{ required: true, message: '请选择订购人', trigger: 'change' }],
                        phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
                        quantity: [
                            { required: true, message: '请输入数量', trigger: 'blur' },
                            { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' },
                            { validator: this.validateQuantity, trigger: 'blur' }
                        ]
                    },
                    isNormalUser: true
                }
            },
            computed: {
                totalAmount() {
                    return this.form.orderDetails.reduce((sum, detail) => {
                        return sum + (detail.price * detail.quantity || 0);
                    }, 0).toFixed(2);
                }
            },
            created() {
                console.log('当前登录用户信息:', window.currentUser);
                this.isNormalUser = !(window.currentUser && window.currentUser.status === 1);
                this.loadUsers();
                if (window.currentUser) {
                    this.form.userId = window.currentUser.id;
                    if (window.currentUser.status === 0) {
                        this.form.phone = window.currentUser.phone || '';
                        this.form.major = window.currentUser.department || '';
                    }
                }
                this.loadBooks();
            },
            methods: {
                loadUsers() {
                    if (window.currentUser && window.currentUser.status === 0) {
                        // 普通用户只显示自己
                        this.users = [window.currentUser];
                        this.form.userId = window.currentUser.id;
                    } else {
                        // 管理员显示所有普通用户
                        axios.get('/user/api/normalUsers').then(res => {
                            this.users = res.data;
                            if (window.currentUser && window.currentUser.id) {
                                this.form.userId = window.currentUser.id;
                            }
                        });
                    }
                },
                loadBooks() {
                    axios.get('/termbook/api/byTermMajor', { params: { term: this.form.term, major: this.form.major } })
                        .then(res => {
                            this.books = res.data;
                        });
                },
                addOrderDetail() {
                    if (!this.form.userId || !this.form.term || !this.form.major) {
                        this.$message.error('请先选择订购人和学期！');
                        return;
                    }
                    this.form.orderDetails.push({
                        bookId: '',
                        quantity: 1,
                        price: 0,
                        availableQuantity: undefined // 新增字段，用于存储可用库存
                    });
                },
                removeOrderDetail(index) {
                    this.form.orderDetails.splice(index, 1);
                    this.calculateTotal();
                },
                handleUserChange(userId) {
                    const user = this.users.find(u => u.id === userId);
                    if (user) {
                        this.form.major = user.department || '';
                        this.form.phone = user.phone || '';
                        this.handleTermMajorChange();
                    } else {
                        this.form.major = '';
                        this.form.phone = '';
                        this.books = [];
                    }
                    // 清空明细已选教材
                    this.form.orderDetails = [];
                },
                handleTermMajorChange() {
                    if (this.form.term && this.form.major) {
                        axios.get('/termbook/api/byTermMajor', { params: { term: this.form.term, major: this.form.major } })
                            .then(res => {
                                this.books = res.data;
                            });
                    } else {
                        this.books = [];
                    }
                    // 清空明细已选教材
                    this.form.orderDetails = [];
                },
                calculateTotal() {
                    // totalAmount 现在是computed属性，不需要手动计算
                },
                // New method to validate for duplicate books
                validateOrderDetails() {
                    const bookIds = new Set();
                    for (const detail of this.form.orderDetails) {
                        if (detail.bookId) {
                            if (bookIds.has(detail.bookId)) {
                                this.$message.error('订单中存在重复的教材，每个教材对于同一用户只能购买一个！');
                                return false;
                            }
                            bookIds.add(detail.bookId);
                        }
                    }
                    return true;
                },
                submitForm() {
                    this.$refs.form.validate(valid => {
                        if (valid) {
                            if (!this.form.userId) {
                                this.$message.error('请选择订购人！');
                                return;
                            }
                            if (!this.form.orderDetails || this.form.orderDetails.length === 0) {
                                this.$message.error('请添加订单明细！');
                                return;
                            }
                            if (!this.validateOrderDetails()) {
                                return;
                            }
                            for (const detail of this.form.orderDetails) {
                                if (!detail.bookId || !detail.quantity || detail.quantity <= 0) {
                                    this.$message.error('订单明细中教材和数量为必填项，且数量必须大于0！');
                                    return;
                                }
                            }

                            // 客户端再次检查库存（以防万一，尽管后端也会检查）
                            for (const detail of this.form.orderDetails) {
                                if (detail.bookId && detail.quantity > detail.stock) {
                                    this.$message.error('教材【' + detail.name + '】库存不足，当前库存：' + detail.stock + '。');
                                    return;
                                }
                            }

                            // 显式构建请求体，确保数据结构符合后端期望
                            const payload = {
                                userId: this.form.userId,
                                phone: this.form.phone,
                                orderDetails: this.form.orderDetails.map(detail => ({
                                    bookId: detail.bookId,
                                    quantity: detail.quantity,
                                    price: detail.price
                                }))
                            };

                            axios.post('/order/add', payload)
                            .then(response => {
                                if (response.data === 'success') {
                                    this.$message.success('订单创建成功！');
                                    // 成功后跳转到订单管理页面
                                    window.location.href = '/order/list';
                                } else {
                                    this.$message.error('订单创建失败！');
                                }
                            })
                            .catch(error => {
                                console.error('订单创建失败:', error);
                                // 如果后端抛出 RuntimeException，错误信息会在 error.response.data 中
                                if (error.response && error.response.data) {
                                    this.$message.error(error.response.data);
                                } else {
                                    this.$message.error('订单创建失败，请检查网络或联系管理员。');
                                }
                            });
                        } else {
                            this.$message.warning('请填写所有必填项并检查输入！');
                            return false;
                        }
                    });
                },
                goBack() {
                    window.history.back();
                },
                resetForm() {
                    this.form = {
                        userId: '',
                        phone: '',
                        orderDetails: [],
                        major: '',
                        term: ''
                    };
                    this.totalAmount = 0;
                    this.$refs.form.resetFields();
                },
                validateQuantity(rule, value, callback) {
                    const index = rule.field.split('.')[1];
                    const detail = this.form.orderDetails[index];

                    if (detail.bookId && detail.stock !== undefined && value > detail.stock) {
                        callback(new Error('数量不能大于库存！当前库存：' + detail.stock));
                    } else {
                        callback();
                    }
                },
                handleBookChange(bookId, index) {
                    if (!bookId) {
                        this.$set(this.form.orderDetails[index], 'stock', 'N/A');
                        this.$set(this.form.orderDetails[index], 'price', 0);
                        return;
                    }
                    // 获取库存
                    axios.get('/inventory/api/book/' + bookId).then(res => {
                        this.$set(this.form.orderDetails[index], 'stock', res.data ? res.data.quantity : 0);
                    });
                    // 获取单价
                    axios.get('/book/detail/' + bookId).then(res => {
                        this.$set(this.form.orderDetails[index], 'price', res.data && res.data.price !== undefined ? res.data.price : 0);
                    });
                }
            }
        });
    </script>
</body>
</html> 